package com.ljw.service;

import com.ljw.po.MembersInfoSearchVo;
import de.otto.flummi.Flummi;
import de.otto.flummi.aggregations.SumAggregationBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import de.otto.flummi.request.SearchRequestBuilder;
import de.otto.flummi.response.SearchResponse;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @Author: lijunwei
 * @Time: 2019/3/21 19:16
 */
@Service
public class CompanyWxGroupSetApiServiceImpl {

    @Autowired
    private Flummi flummi;

    public SearchResponse searchBrandMemberResponse(Long brandId, Long guideId, List<Long> storeList) {

        de.otto.flummi.query.BoolQueryBuilder boolQueryBuilder = de.otto.flummi.query.QueryBuilders.bool();
        // 品牌
        if (brandId != null) {
            boolQueryBuilder.must(de.otto.flummi.query.QueryBuilders.termQuery("brandId", brandId));
        }
        // 导购id
        if (guideId != null) {
            boolQueryBuilder.must(de.otto.flummi.query.QueryBuilders.termQuery("serviceGuideId", guideId));
        }
        // 店铺集合
        if (storeList != null) {
            List<String> strStoreList = (List<String>) CollectionUtils.collect(storeList, input -> String.valueOf(input));
            boolQueryBuilder.must(de.otto.flummi.query.QueryBuilders.termsQuery("serviceStoreId", strStoreList));
        }

        // 查询当前品牌的累计成交额
        SearchRequestBuilder searchBrandRequestBuilder = flummi.prepareSearch("t_mbr_members").setTypes("doc")
                .setQuery(boolQueryBuilder.build())
                .addAggregation(new SumAggregationBuilder("consumeAmountBrandAllSum", "consumeAmountAll"));

        SearchResponse searchBrandResponse = searchBrandRequestBuilder.execute();
        return searchBrandResponse;
    }


    public BoolQueryBuilder getESWhere(MembersInfoSearchVo infoSearchVo, BoolQueryBuilder builder) {
        // valid
        builder.filter(QueryBuilders.matchQuery("valid", true));

        // 企业
        if (null != infoSearchVo.getSysCompanyId()) {
            builder.filter(QueryBuilders.matchQuery("sysCompanyId", infoSearchVo.getSysCompanyId()));
        }

        // 品牌号
        if (null != infoSearchVo.getBrandId()) {
            builder.filter(QueryBuilders.matchQuery("brandId", infoSearchVo.getBrandId()));
        }

        // 姓名
        if (null != infoSearchVo.getName()) {
            builder.filter(QueryBuilders.matchQuery("name", infoSearchVo.getName()));
        }

        // 手机号
        if (null != infoSearchVo.getPhone()) {
            builder.filter(QueryBuilders.matchQuery("phone.keyword", infoSearchVo.getPhone()));
        }
        return builder;
    }

}
